import React, { useEffect, useState } from 'react';
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  Space,
  Card,
  Divider,
  Typography,
  message,
  Cascader,
  DatePicker,
  TreeSelect,
  InputNumber,
  Popconfirm,
} from 'antd';
import {
  SearchOutlined,
  UndoOutlined,
  EditOutlined,
  DeleteOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SyncOutlined,
  ClockCircleOutlined,
  AuditOutlined,
} from '@ant-design/icons';
import area from '@/components/staticFile/region_options.json';
import product from '@/components/staticFile/product_options.json';
import chinaEconomy from '@/components/staticFile/industry_classification_options.json';
import dayjs from 'dayjs';
import { getThirdReport, pageUsers, removeUsers, update, userProgress } from '@/services/apis/companyRegister';
import { useModel } from '@umijs/max';
import CompanyAllInfosPage from '../WorkOfRtaing/modal';
const { Title, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;

// 状态选项
let STATUS_OPTIONS = [
  { value: 'pending', label: '已处理' },
  { value: 'approved', label: '未处理' },
  // { value: 'rejected', label: '不通过' },
  // { value: 'returned', label: '已退回' },
];



const RatingReport: React.FC = () => {
  // 状态管理：新增进度相关状态
  const [enterprises, setEnterprises] = useState([]);
  const [searchForm] = Form.useForm();
  const { initialState, setInitialState } = useModel('@@initialState');
  const {
    modalProps,
    setModalProps,
  } = useModel("WorkOfRate.modal")

  const [pageProps, setPageProps] = useState<{ current: number, pageSize: number, total: number }>({
    current: 1,
    pageSize: 10,
    total: 0
  })

  // 搜索处理
  const handleSearch = async () => {
    searchUsers({ ...searchForm.getFieldsValue(), current: pageProps.current, size: pageProps.pageSize })
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    searchUsers({ current: pageProps.current, size: pageProps.pageSize })
  };

  // 打开编辑弹窗：新增关闭进度弹窗逻辑
  const handleEdit = (record: any, title: string) => {
    setModalProps(prev => ({ ...prev, visible: true, record, title }))
  };

  const searchUsers = (values: any) => {
    getThirdReport({
      ...values,
      loginInArea: initialState?.currentUser.data.loginInArea,
      userType: initialState?.currentUser.data.userType,
    }).then(res => {
      const { code, data } = res
      if (code == "0") {
        setEnterprises(data.records)
        setPageProps({
          current: data.current,
          pageSize: data.size,
          total: data.total
        })
        //message.success("请求成功")
      }
    })
  }
  useEffect(() => {
    searchUsers({ current: pageProps.current, size: pageProps.pageSize })
    if (initialState?.currentUser.data.userType == "rate") {
      STATUS_OPTIONS = [
        { value: '%待评测', label: '评测机构待评测' },
        { value: '%已评测', label: '评测机构已评测' },
      ];
    }
    if (initialState?.currentUser.data.userType == "audit") {
      STATUS_OPTIONS = [
        { value: '%待审计', label: '审计机构待审计' },
        { value: '%已审计', label: '审计机构已审计' },
      ];
    }
    if (initialState?.currentUser.data.userType == "accept") {
      STATUS_OPTIONS = [
        { value: '%待验收', label: '验收机构待验收' },
        { value: '%已验收', label: '验收机构已验收' },
      ];
    }
  }, [])
  const usersPageOnchange = (current: any, pageSize: any) => {
    searchUsers({ ...searchForm.getFieldsValue(), current, size: pageSize })
  }
  // 表格列配置：新增“进度”按钮（在“审核”后）
  const columns = [
    {
      title: '序号',
      dataIndex: 'serialNumber',
      key: 'serialNumber',
      width: "10%",
      align: 'center',
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '企业名称',
      dataIndex: 'companyName',
      key: 'companyName',
      width: "15%",
      ellipsis: true,

    },
    {
      title: '联系人',
      dataIndex: 'concatPerson',
      key: 'concatPerson',
      width: "15%",
      ellipsis: true,

    },
    {
      title: '联系电话',
      dataIndex: 'concatPhone',
      key: 'concatPhone',
      width: "15%",
      ellipsis: true,

    },
    {
      title: '环节',
      dataIndex: 'link',
      key: 'link',
      width: "10%",
      align: 'center',
      ellipsis: true,

    },
    {
      title: '状态',
      dataIndex: 'auditStatus',
      key: 'auditStatus',
      width: "10%",
      align: 'center',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'operation',
      width: "20%",// 加宽操作列容纳4个按钮
      align: 'center',
      render: (_: any, record: any) => (
        <Space size={2}>
          <Button
            type="primary"
            size="small"
            disabled={record.auditStatus == "评测机构已评测" || record.auditStatus == "审计机构已审计"|| record.auditStatus == "验收机构已验收"}
            icon={<EditOutlined />}
            onClick={() => handleEdit(record, "上传报告")}
          >
            上传报告
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="pilot-enterprise-management" style={{ padding: '20px' }}>
      <div
        style={{
          fontSize: 16,
          fontWeight: 500,
          color: '#1f2937',
          marginBottom: 12,
        }}
      >
        提交报告
      </div>

      {/* 搜索栏 */}
      <Card style={{ marginBottom: 16 }}>
        <Form form={searchForm} layout="inline" onFinish={handleSearch}>
          <Form.Item name="enterpriseName" label="企业名称">
            <Input allowClear placeholder="请输入企业名称" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item name="auditStatus" label="状态">
            <Select allowClear placeholder="请选择状态" style={{ width: 160 }}>
              {STATUS_OPTIONS.map((option) => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button onClick={handleReset} icon={<UndoOutlined />}>
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>

      <Card
        style={{
          borderRadius: 12,
          boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
          // height: 'calc(100vh - 170px)', // 精确高度，保证内部滚动
          // overflowY: 'auto', // 内部滚动
          padding: '24px',
        }}
      >
        {/* 企业列表 */}
        <Table
          columns={columns as any}
          dataSource={enterprises}
          rowKey="id"
          pagination={{
            pageSize: pageProps.pageSize,
            current: pageProps.current, total: pageProps.total, showSizeChanger: true,
            onChange: usersPageOnchange
          }}
          bordered
          scroll={{ y: 'calc(100vh - 450px)' }}
          locale={{ emptyText: '暂无试点企业数据' }}
        />
      </Card>
      <CompanyAllInfosPage searchCallFun={handleSearch} />
    </div>
  );
};

export default RatingReport;
